package com.recource.interceptor;

import com.recource.annonation.Login;
import com.recource.dao.ConfigDao;
import com.recource.domain.Config;
import com.recource.domain.Users;
import com.recource.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yujie
 * @createTime 2023/1/5 15:25
 * @description
 */
@Component
public class ConfigInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private ConfigDao configDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Class<?> clazz = handlerMethod.getBeanType();
            //检查调用的方法是否有login注解
            Login annotation1 = clazz.getAnnotation(Login.class);
            if(Objects.nonNull(annotation1)){
                RequestMapping annotation = handlerMethod.getMethodAnnotation(RequestMapping.class);
                Config config = new Config();
                String[] value = annotation.value();
                String join = StringUtils.join(value, ",");
                config.setApi(join);
                config.setUid(hostHolder.getUser().getId());
                config.setDate(new Date());
                configDao.insert(config);
                return true;
            }

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
